//
//  CollectView.m
//  GC_OC
//
//  Created by 叶建辉 on 2022/7/11.
//

#import "CollectView.h"


@protocol collectCellDelegate <NSObject>

-(void)slidingDirection;
-(void)clickWithTag:(NSInteger)tag;

@end

@interface collectCell : UITableViewCell

@property(nonatomic,weak)id<collectCellDelegate>delegate;

@property(nonatomic,strong)NSDictionary *resDic;

@property(nonatomic,assign)NSInteger selectnum;
@property(nonatomic,strong)UILabel *nameLab;
@end

@interface collectCell ()


@property(nonatomic,strong)UILabel *classLab;
@property(nonatomic,strong)UILabel *timeLab;

@property(nonatomic,strong)UIImageView *arrowImg;
@property(nonatomic,strong)UIView *labelvs;

@end

@implementation collectCell

-(UIView *)labelvs{
    if (!_labelvs) {
        _labelvs = [UIView new];
    }
    return _labelvs;
}

-(UILabel *)nameLab{
    if (!_nameLab) {
        _nameLab = [UILabel new];
        _nameLab.textColor = [UIColor colorWithWhite:.2 alpha:1];
        _nameLab.textAlignment = NSTextAlignmentLeft;
    }
    return _nameLab;
}

-(UILabel *)timeLab{
    if (!_timeLab) {
        _timeLab = [UILabel new];
        _timeLab.textColor = [UIColor colorWithWhite:.75 alpha:1];
//        _timeLab.textAlignment = NSTextAlignmentRight;
    }
    return _timeLab;
}

-(UILabel *)classLab{
    if (!_classLab) {
        _classLab = [UILabel new];
        _classLab.textColor = [UIColor colorWithWhite:.75 alpha:1];
//        _classLab.textAlignment = NSTextAlignmentRight;
    }
    return _classLab;
}

-(UIImageView *)arrowImg{
    if (!_arrowImg) {
        _arrowImg = [UIImageView new];
        _arrowImg.image = [UIImage imageNamed:@"time"];
//        _arrowImg.backgroundColor = [UIColor greenColor];
    }
    return _arrowImg;
}

-(void)setSelectnum:(NSInteger)superIndex{
    _selectnum = superIndex;
    if (_selectnum == self.tag) {
        _nameLab.textColor = [UIColor colorWithHex:@"#0091FF"];
    }else{
        _timeLab.textColor = [UIColor colorWithWhite:.75 alpha:1];
    }
}

-(void)setResDic:(NSDictionary *)resDic{
    _resDic = resDic;
    _nameLab.text = [NSString setSafeString:_resDic[@"name"]];
    _timeLab.text = [self getVideoLengthFromTimeLength:[[NSString setSafeString:_resDic[@"audio_num"]] floatValue]];
    _classLab.text = [NSString stringWithFormat:@"%@-%@",[NSString setSafeString:_resDic[@"category_name_1"]],[NSString setSafeString:_resDic[@"category_name"]]];
    
    NSArray *labels = [NSArray setSafeArr:_resDic[@"lables"]];
    if (labels.count>0) {
        for (UIView *v in _labelvs.subviews) {
            [v removeFromSuperview];
        }
        
        for (int i = 0; i < labels.count; i++) {
            
            UIView *vv = [UIView new];
            vv.tag = 400+i;
            vv.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
            [_labelvs addSubview:vv];
            
            UILabel *tipsLab = [UILabel new];
            tipsLab.text = labels[i];
            tipsLab.textColor = [UIColor colorWithWhite:.75 alpha:1];
            tipsLab.textAlignment = NSTextAlignmentCenter;
            tipsLab.tag = 300+i;
            [_labelvs addSubview:tipsLab];
        }
        UILabel *jLab = [UILabel new];
        jLab.text = @"...";
        jLab.textColor = [UIColor colorWithWhite:.75 alpha:1];
        jLab.textAlignment = NSTextAlignmentCenter;
        jLab.tag = 500;
        [_labelvs addSubview:jLab];
    }
}

-(NSString *)getVideoLengthFromTimeLength:(float)timeLength{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timeLength];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    NSLog(@"~~components.hour~~>%zd",components.hour);
    if (components.hour == 0) {
        return [NSString stringWithFormat:@"%@:%@:%@",components.hour < 10?[NSString stringWithFormat:@"0%zd",components.hour]:[NSString stringWithFormat:@"%zd",components.hour],components.minute < 10?[NSString stringWithFormat:@"0%zd",components.minute]:[NSString stringWithFormat:@"%zd",components.minute],components.second < 10?[NSString stringWithFormat:@"0%zd",components.second]:[NSString stringWithFormat:@"%zd",components.second]];
    }
    return [NSString stringWithFormat:@"%@:%@",components.minute < 10?[NSString stringWithFormat:@"0%zd",components.minute]:[NSString stringWithFormat:@"%zd",components.minute],components.second < 10?[NSString stringWithFormat:@"0%zd",components.second]:[NSString stringWithFormat:@"%zd",components.second]];
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:self.nameLab];
        [self addSubview:self.timeLab];
        [self addSubview:self.classLab];
        [self addSubview:self.arrowImg];
        [self addSubview:self.labelvs];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
//    HEIGHTDiv*.035+WIDTHDiv*.035
    
    
    
    
    CGSize titleSize = [[NSString stringWithFormat:@"%@0",_timeLab.text] sizeWithFont:[UIFont systemFontOfSize:self.zf_height*.2] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    
    _timeLab.frame = CGRectMake(self.zf_width*.98-titleSize.width, self.zf_height*.1, titleSize.width, self.zf_height*.4);
    _timeLab.font = [UIFont systemFontOfSize:self.zf_height*.2];
    
    _arrowImg.frame = CGRectMake(self.zf_width*.96-titleSize.width-self.zf_height*.3, self.zf_height*.15, self.zf_height*.3, self.zf_height*.3);
    
    CGSize classSize = [[NSString stringWithFormat:@"%@0",_classLab.text] sizeWithFont:[UIFont systemFontOfSize:self.zf_height*.15] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    _classLab.frame = CGRectMake(self.zf_width*.98-classSize.width, self.zf_height*.6, classSize.width, self.zf_height*.2);
    _classLab.font = [UIFont systemFontOfSize:self.zf_height*.15];
    
    NSArray *labels = [NSArray setSafeArr:_resDic[@"lables"]];
    
    _nameLab.frame = CGRectMake(self.zf_height*.5, labels.count>0?-self.zf_height*.15:0, self.zf_width-self.zf_height*.9-titleSize.width, self.zf_height);
    _nameLab.font = [UIFont systemFontOfSize:_nameLab.zf_height*.25];
        
    float labw = self.zf_width*.93 - classSize.width - _nameLab.zf_left;
    
    _labelvs.frame = CGRectMake(_nameLab.zf_left, self.zf_height*.6, labw, self.zf_height*.2);
//    _labelvs.backgroundColor = [UIColor greenColor];
    
    if (labels.count>0) {
        _labelvs.hidden = NO;
        float lw = 0;
        for (int i = 0; i < labels.count; i++) {
            
            UILabel *tipsLab = [_labelvs viewWithTag:300+i];
            CGSize tipsSize = [[NSString stringWithFormat:@"0%@",tipsLab.text] sizeWithFont:[UIFont systemFontOfSize:self.zf_height*.15] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
            tipsLab.frame = CGRectMake(lw, 0, tipsSize.width, self.zf_height*.2);
            tipsLab.font = [UIFont systemFontOfSize:self.zf_height*.15];
            lw+=(tipsSize.width+self.zf_height*.05);
            
            UIView *vv = [_labelvs viewWithTag:400+i];
            vv.frame = tipsLab.frame;
            
            CGSize jSize = [[NSString stringWithFormat:@"..."] sizeWithFont:[UIFont systemFontOfSize:self.zf_height*.15] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
            
            if (lw>labw-jSize.width) {
                vv.hidden = YES;
                tipsLab.hidden = YES;
                UILabel *jLab = [_labelvs viewWithTag:500];
                jLab.frame = CGRectMake(lw-(tipsSize.width+self.zf_height*.1), 0, jSize.width,  self.zf_height*.2);
            }
        }
        
    }else{
        _labelvs.hidden = YES;
    }
    
}

-(void)dealloc{
    
}

@end

@interface CollectView ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UIView *navView;

@property(nonatomic,strong)UIImageView *emptyView;



@end


@implementation CollectView

-(UIImageView *)emptyView{
    if (!_emptyView) {
        _emptyView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"empty_show"]];
        _emptyView.hidden = YES;
    }
    return _emptyView;
}


-(UIView *)navView{
    if (!_navView) {
        _navView = [UIView new];
        _navView.backgroundColor = [UIColor colorWithHex:@"#0091FF"];
        
        NSArray*imgStr = @[@"back",@"collect_showwhite",[[NSUserDefaults standardUserDefaults] integerForKey:@"issequence"]==1?@"order_za":@"order_az"];
        
        for (int i = 0; i < 3; i++) {
            UIButton *btn = [UIButton new];
//            btn.backgroundColor = [UIColor greenColor];
            btn.tag = 100+i;
            [btn setImage:[UIImage imageNamed:imgStr[i]] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_navView addSubview:btn];
        }
        
        UILabel *titleLab = [UILabel new];
        titleLab.textColor = [UIColor whiteColor];
        titleLab.tag = 200;
        [_navView addSubview:titleLab];
        
    }
    return _navView;
}

-(void)changeazView:(BOOL)isshow{
    UIButton *btn = [_navView viewWithTag:102];
    if (!isshow) {
        [btn setImage:[UIImage imageNamed:@"order_za"] forState:UIControlStateNormal];
    }else{
        [btn setImage:[UIImage imageNamed:@"order_az"] forState:UIControlStateNormal];
    }
}

-(void)changeshowView:(BOOL)isshow{
    UIButton *btn = [_navView viewWithTag:101];
    if (isshow) {
        [btn setImage:[UIImage imageNamed:@"collect_show"] forState:UIControlStateNormal];
    }else{
        [btn setImage:[UIImage imageNamed:@"collect_showwhite"] forState:UIControlStateNormal];
    }
}

-(void)btnClick:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(ClickOnTheButtonTag:)]) {
        [self.delegate ClickOnTheButtonTag:sender.tag - 100];
    }
}

-(void)setSelectNum:(NSInteger)selectNum{
    _selectNum = selectNum;
    [_tableView reloadData];
}

-(void)setDatas:(NSMutableArray *)datas{
    _datas = datas;
    UILabel *titleLab = [_navView viewWithTag:200];
    if(_datas.count>0){
        _tableView.hidden = NO;
        _emptyView.hidden = YES;
        NSString *attStr = [NSString stringWithFormat:@"所有收藏(%zd)",_datas.count];
        NSMutableAttributedString *attributedStr01 = [[NSMutableAttributedString alloc] initWithString: attStr];
         
        //添加属性
         
        //分段控制，最开始4个字符颜色设置成蓝色
        [attributedStr01 addAttribute: NSForegroundColorAttributeName value: [UIColor whiteColor] range: NSMakeRange(0, 4)];
        //分段控制，第5个字符开始的3个字符，即第5、6、7字符设置为红色
        [attributedStr01 addAttribute: NSForegroundColorAttributeName value:[UIColor colorWithHex:@"#32C5FF"] range: NSMakeRange(4, attStr.length-4)];
         
        //赋值给显示控件label01的 attributedText
        titleLab.attributedText = attributedStr01;
         
        
        [_tableView reloadData];
    }else{
        _tableView.hidden = YES;
        _emptyView.hidden = NO;
        NSString *attStr = [NSString stringWithFormat:@"所有收藏"];
        titleLab.text = attStr;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return HEIGHTDiv*.002;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return .0001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
    
}

-(void)clickWithTag:(NSInteger)tag{
    [_tableView reloadData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.delegate respondsToSelector:@selector(ClickOnTheIndexPathRow:)]) {
        [self.delegate ClickOnTheIndexPathRow:indexPath.section];
    }
    collectCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yinfu"]];
    CGPoint fromCenter =  [cell.nameLab convertPoint:CGPointMake(cell.nameLab.frame.size.width * 0.5f, cell.nameLab.frame.size.height * 0.5f) toView:keyWindow];
    imageV.center = fromCenter;
    imageV.size = CGSizeMake(18, 22);
    
    [[PurchaseCarAnimationTool shareTool] startAnimationandView:imageV
                                                           rect:imageV.frame
                                                    finisnPoint:CGPointMake(ScreenWidth / 4 * 2.5, SCREEN_HEIGHT - GCtabbarHeight -  50)
                                                    finishBlock:^(BOOL finish) {}];
}

#pragma mark 左滑删除

-(UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{
    UIContextualAction * deleteAction =  [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        if ([self.delegate respondsToSelector:@selector(DeleteOnTheIndexPathRow:)]) {
            [self.delegate DeleteOnTheIndexPathRow:indexPath.section];
        }
        
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    UISwipeActionsConfiguration *Configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    return Configuration;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (HEIGHTDiv*.05+WIDTHDiv*.05);
}

static NSString *CellIdentifier = @"CELL";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    collectCell *cell = [[collectCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.backgroundColor = [UIColor whiteColor];
    cell.tag = indexPath.section;
    cell.selectnum = _selectNum;
    cell.resDic = [NSDictionary setSafeDictionary:_datas[indexPath.section]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.delegate = self;
    return cell;
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    _tableView.contentSize = CGSizeMake(WIDTHDiv, (HEIGHTDiv*.035+WIDTHDiv*.035)*(_datas.count+3));
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    _navView.frame = CGRectMake(0, 0, WIDTHDiv, SafeAreaTopHeight);
    _tableView.frame = CGRectMake(0, SafeAreaTopHeight, self.frame.size.width, self.frame.size.height-SafeAreaTopHeight);
    
    for (int i = 0; i < 3; i++) {
        UIButton *btn = [_navView viewWithTag:100+i];
        if (i == 0) {
            btn.frame = CGRectMake(5, _navView.zf_height-35,30 , 30);
        }else if (i == 1) {
            btn.frame = CGRectMake(_navView.zf_width-85, _navView.zf_height-35,30 , 30);
        }else{
            btn.frame = CGRectMake(_navView.zf_width-45, _navView.zf_height-35,30 , 30);
        }
    }
    
    UILabel *titleLab = [_navView viewWithTag:200];
    titleLab.frame = CGRectMake(40, _navView.zf_height-35, WIDTHDiv*.5, 30);
    
    _emptyView.frame = CGRectMake(WIDTHDiv*.3, (self.zf_height-WIDTHDiv*.4)*.4, WIDTHDiv*.4, WIDTHDiv*.4);
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        _datas = [NSMutableArray array];
        _selectNum = -1;
        [self addSubview:self.emptyView];
        [self addSubview:self.navView];
        [self addSubview:self.tableView];
    }
    return self;
}


@end
